#############################################################################
#Yuhua Wang#
#The Rise and Fall of Imperial China: The Social Origins of State Development#
#Princeton University Press, 2022#
############################################################################

############################################################################
#Chapter 5#
############################################################################


######################################
#Figure 5.1: Major Politicians during the Wang Anshi Reform#
######################################

rm(list = ls())
library(foreign) 
library(ggplot2) 
require(ggplot2)
library(ggrepel) 
library(plyr)
require(scales)

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 5/data/")

######################################
#(a) Policy Attitudes#
######################################

politician <- read.dta("Wang Anshi reform data_wk.dta")

attach(politician)

support <- ggplot(politician, aes(x = support_continuous)) +  
  geom_histogram(aes(y = (..count..)/sum(..count..)), color="black", fill="grey") + 
  scale_y_continuous(name="Percent",labels = scales::percent,limits=c(0,0.6), breaks=c(0,0.1,0.2,0.3,0.4,0.5,0.6))+
  scale_x_continuous(name="Support for Reform", limits=c(-0.05,1.05), breaks=c(0,0.5,1))+
  theme_minimal()+
  theme(
    axis.title.x = element_text(size = 20),
    axis.text.x = element_text(size = 15),
    axis.text.y = element_text(size = 15),
    axis.title.y = element_text(size = 20))

support

######################################
#(b) Career Trajectories#
######################################

data <- read.dta("career path.dta")

attach(data)

data$treatment <- as.factor(data$support_dummy)

ggplot(data=data, aes(x=year, y=smoothedrank, group=treatment,color=treatment,linetype=treatment)) + 
  geom_point() + geom_line() +geom_ribbon(aes(ymin=data$smoothedmin95, ymax=data$smoothedmax95), linetype=2, alpha=0.1) +
  scale_color_manual(values=c("#F8766D",  "#619CFF", "#00BA38"))+
  scale_x_continuous(name="Year", limits=c(1068,1085), breaks=c(1070,1075,1080,1085)) +
  scale_y_continuous(name="Average Rank",limits=c(1,6), breaks=c(0,1,2,3,4,5,6)) +
  annotate(geom="text", x = 1070, y=3, label = "Opponents",size=8)+
  annotate(geom="text", x = 1070, y=2.3, label = "Supporters", size=8)+
  annotate(geom="text", x = 1070, y=1.6, label = "Unknown", size=8)+
  theme_bw()+
  theme(
    axis.title.x = element_text(size = 20),
    axis.text.x = element_text(size = 15),
    axis.text.y = element_text(size = 15),
    axis.title.y = element_text(size = 20),
    panel.background = element_rect(fill = "#f5f5f2", color = NA))+
  theme(legend.position="none")


################################
#Figure 5.2: Two Politicians’ Kinship Networks#
################################

################################
#(a) Wang Anshi (Reform Leader)#
################################

rm(list = ls())
library(igraph)
library(statnet)
library("network")

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 5/data/")

#read in egelist
rawedgeswang<-read.csv("Wang Anshi edgelist.csv")

#turn edgelist into adjacency matrix
matrixwang <-as.matrix(get.adjacency(graph.data.frame(rawedgeswang)))

#write in a csv file
write.csv(matrixwang,"Wang Anshi adjmatrix.csv", row.names = FALSE)

# detach igraph package
detach("package:igraph")

#Read in Adjacency Matrix

net.adj.wang <- as.matrix(matrixwang) 

# load in vertex attributes

#orignal coordinates
nodeInfoWANG <- read.csv(file="Wang node attributes.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.wang) # peek at matrix 
print(nodeInfoWANG)  # peek at attribute data

# create undirected network object from matrix

net_wang<-network(net.adj.wang, directed=FALSE, matrix.type="adjacency")

# it read in vertex names from matrix col names ...
network.vertex.names(net_wang)

# ATTACHING VERTEX ATTRIBUTES

# load in other attributes 
net_wang%v%"lon" <- nodeInfoWANG$x
net_wang%v%"lat" <- nodeInfoWANG$y


# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_wang)

summary(net_wang)

gden(net_wang)

degwang <- degree(net_wang,gmode="graph")

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}

#A peek of Wang Anshi's kinship network#

op<-par(mar=c(0,0,0,0))
plot(net_wang,vertex.cex=rescale(degwang,0.5,3))
par(op)

################################
#(b) Lu ̈ Gongzhu (Opposition Leader)#
################################

library(igraph)
library(statnet)
library("network")

#Change this to your local directory#

setwd("/Users/ywang/Dropbox/Book Project on State Building/Princeton UP/Replication Package/Chapter 5/data/")

#read in egelist
rawedgeslv<-read.csv("Lv Gongzhu edgelist.csv")

#turn edgelist into adjacency matrix
matrixlv <-as.matrix(get.adjacency(graph.data.frame(rawedgeslv)))

#write in a csv file
write.csv(matrixlv,"Lv Gongzhu adjmatrix.csv", row.names = FALSE)

# detach igraph package
detach("package:igraph")

#Read in Adjacency Matrix

net.adj.lv <- as.matrix(matrixlv) 

# load in vertex attributes

#orignal coordinates
nodeInfoLV <- read.csv(file="Lv node attributes.csv",header=TRUE,stringsAsFactors=FALSE)

print(net.adj.lv) # peek at matrix 
print(nodeInfoLV)  # peek at attribute data

# create undirected network object from matrix

net_lv<-network(net.adj.lv, directed=FALSE, matrix.type="adjacency")

# it read in vertex names from matrix col names ...
network.vertex.names(net_lv)

# ATTACHING VERTEX ATTRIBUTES

# load in other attributes 
net_lv%v%"lon" <- nodeInfoLV$x
net_lv%v%"lat" <- nodeInfoLV$y

# Note: order of attributes in the data frame MUST match vertex ids
# otherwise the attribute will get assigned to the wrong vertex

# check that they got loaded
list.vertex.attributes(net_lv)

summary(net_lv)

gden(net_lv)

deg <- degree(net_lv,gmode="graph")

rescale<-function(nchar,low,high){
  min_d<-min(nchar)
  max_d<-max(nchar)
  rscl<-((high-low)*(nchar-min_d))/(max_d-min_d)+low
  rscl
}

#A peek of Lv Gongzhu's kinship network#

op<-par(mar=c(0,0,0,0))
plot(net_lv,vertex.cex=rescale(deg,0.5,3))
par(op)

# Add Song map

library('maps')
library('geosphere')
library(maptools)
library(foreign)
library(PBSmapping)
library(network)
library(maps)
library(statnet)
require(rgdal)

song <- importShapefile("songprovinces1080_gr8.shp")

proj.abbr <- attr(song, "projection")

#Creat the Song map#
plotPolys(song, projection=proj.abbr, border="grey",
          xlab="", ylab="",col="#f5f5f2", tckLab = FALSE,axes=FALSE)

#Layer on Wang Anshi's kinship network (Figure 5.2 (a))#
plot.network(net_wang,  # pass in the network
             # don't erase the map before drawing the network
             new=FALSE, 
             # get coordiantes from vertices and pass in as 2-col matrix
             coord=cbind(net_wang%v%"lon",net_wang%v%"lat"),  
             # ---- all the rest of these are optional to make it look nice ------
             # set a semi-transparent edge color
             vertex.col="darkgreen",
             vertex.cex=rescale(degwang,0.5,3),
             vertex.border='darkgreen',
             edge.col="grey",
             # please don't jitter the points around
             jitter=FALSE)

#output pdf in 6.66*7.46

#Creat the Song map#
plotPolys(song, projection=proj.abbr, border="grey",
          xlab="", ylab="",col="#f5f5f2", tckLab = FALSE,axes=FALSE)

#Layer on Lv Gongzhu's kinship network (Figure 5.2 (b))#
plot.network(net_lv,  # pass in the network
             # don't erase the map before drawing the network
             new=FALSE, 
             # get coordiantes from vertices and pass in as 2-col matrix
             coord=cbind(net_lv%v%"lon",net_lv%v%"lat"),  
             # ---- all the rest of these are optional to make it look nice ------
             # set a semi-transparent edge color
             vertex.cex=rescale(deg,1,4),
             vertex.col="red",
             vertex.border='red',
             edge.col="grey",
             #usecurve=TRUE,
             #edge.curve = 0.001,
             # please don't jitter the points around
             jitter=FALSE)

#output pdf in 6.66*7.46


